<template>
  <EcDialog v-model="dialogVisible" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="full-form"
             label-width="auto"
             status-icon>

      <el-form-item label="对应商户：" prop="mid">
        <el-select
          v-model="formData.mid"
          placeholder="请选择"
        >
          <el-option
            filterable
            v-for="item in options"
            :key="item.id"
            :label="item.full_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="IP地址：" prop="ip">
        <el-input v-model="formData.ip" placeholder="请输入IP地址"/>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-radio-group v-model="formData.status" >
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="支付方式：" prop="type">
        <el-radio-group v-model="formData.type" >
          <el-radio :value="1">收款</el-radio>
          <el-radio :value="2">代付</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import {computed, nextTick, reactive, ref} from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import {
  getMenuList,
  SysMenuData,
  sysMenuTreeList, sysRoleAdd,
  SysRoleData,
  sysRoleInfo,
  sysRoleSaveOrUpdate, sysRoleUpdate
} from '@/api/api-sys.ts';
import useDialog from '@/hooks/use-dialog.ts';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import {merchantList, whiteAdd, whiteEdit, whiteInfo} from "@/api/api-store.ts";

defineOptions({name: 'SysRoleForm'});

const formRef = ref<FormInstance>();
const formLoading = ref(false) // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 默认表单数据
let defaultForm: SysRoleData = {
  id: 0,
  mid: '',
  status:1,
  ip:'',
  type:1
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  ip: [{required: true, message: 'ip地址不能为空', trigger: 'blur'}],
  mid: [{required: true, message: '商户不能为空', trigger: 'blur'}],
});
const options=ref<array>([])
const getOptions=async ()=>{
  const {body} = await merchantList({
    action:'list',
    page: 1,
    size: 999,
  });
  options.value=body.list
}
/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value || menuTreeLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = ref();

const menuData = ref<SysMenuData[]>([]);
const menuTreeRef = ref();
const menuTreeProps = {
  label: 'title',
  children: 'child',
};
const menuTreeLoading = ref(false)
const reverseWithChild=(arr:any)=> {
  return arr.slice().reverse().map(item => {
    if (Array.isArray(item.child)) {
      item.child = reverseWithChild(item.child);
    }
    return item;
  });
}
/** 打开弹窗 */
const open = async (mode: number, row?: any) => {
  dialogMode.value = mode;
  dialogTitle.value = '白名单';
  dialogVisible.value = true;
  await getOptions()
  // 重置表单
  resetForm();
  isCreate.value=row.id
  // 加载信息
  if (row.id) {
    formLoading.value = true
    whiteInfo({id:row.id,action:'info'}).then(res=>{
      formLoading.value = false
      console.log(res,888)
      formData.value=res.body
    })

    try {

    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['success']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })

    // 提交数据
    if(isCreate.value==undefined){

      whiteAdd(formData.value, {action:'add'}).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('success')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())
    }else{
      whiteEdit(formData.value, {action:'update'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('success')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }
  });
};

/** 重置表单 */
const resetForm = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-checkbox-group .el-checkbox {
    float: left;
    width: 150px;
    padding-right: 10px;
    margin: 0;
  }

  .permission-tree {
    width: 100%;
  }
}
</style>
